package com.ldc.common.common;

import android.graphics.Color;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.IdRes;
import androidx.annotation.IntDef;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.recyclerview.widget.RecyclerView;

public class CommonRecyclerViewHolder extends RecyclerView.ViewHolder {

    private final SparseArray<View> sparseArray;

    public CommonRecyclerViewHolder(@NonNull View itemView) {
        super(itemView);
        sparseArray = new SparseArray<>();
    }


    public static CommonRecyclerViewHolder get(ViewGroup parent, @LayoutRes int layoutId) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        return new CommonRecyclerViewHolder(view);
    }

    public View findViewById(@IdRes int id) {
        View view = sparseArray.get(id);
        if (null == view) {
            view = itemView.findViewById(id);
            sparseArray.put(id, view);
        }
        return view;
    }

    public void setText(@IdRes int id, @StringRes int text) {
        setText(id, itemView.getContext().getResources().getString(text));
    }

    public void setText(@IdRes int id, String text) {
        View view = findViewById(id);
        if (view instanceof TextView) {
            ((TextView) view).setText(text);
        }
    }


    public void setVisibility(@IdRes int id, boolean visible) {
        View view = findViewById(id);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    public void setTextSize(@IdRes int id, int size) {
        View view = findViewById(id);
        if (view instanceof TextView) {
            ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        }
    }

    public void setTextColorRes(@IdRes int id, @ColorInt int color) {
        View view = findViewById(id);
        if (view instanceof TextView) {
            ((TextView) view).setTextColor(color);
        }
    }
}
